package com.chixing.day11_exception.work;

public class ListNode {
    private int val;
    ListNode next;
    private ListNode() {}
    private ListNode(int val) {
        this.val = val;
    }
     ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = dummy.next;
        return ans;
    }

    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }


}


/*
public class ListNode {
    ListNode first;
    ListNode last;
    int size = 0;
    int val;
    ListNode next;
    ListNode(){}
    ListNode(int...val){
        for (int i = 0;i < val.length;i++){
            add(val[i]);
        }
    }
    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
    public void add(int val){
        if (first == null){
            first = new ListNode(val,null);
            last = first;
        }
        else{
            ListNode oldLast = last;
            last = new ListNode(val,null);
            oldLast.next = last;
        }
        size++;
    }

}
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = head.first;
        for (int i = 1;i <= head.size - n - 1;i++){
            node = node.next;
        }
        ListNode oldLast = node.next.next;
        node.next = null;
        node.next = oldLast;
        show(head.first);
        return node;
    }
    public void show(ListNode first){
        ListNode node2 = first;
        while(node2 != null){
            System.out.println(node2.val);
            node2 = node2.next;
        }

    }
}*/
